<template>
	<view class="profile-container">
		<!-- 用户信息区域 -->
		<view class="user-info-section">
			<view class="avatar">
				<text class="avatar-text">{{ getAvatarText() }}</text>
			</view>
			<view class="user-details">
				<text class="nickname">{{ userInfo.nickname || '未登录' }}</text>
				<text class="phone">{{ getMaskedPhone() }}</text>
			</view>
		</view>

		<!-- 统计信息区域 -->
		<view class="stats-section">
			<view class="stats-title">我的统计</view>
			<view class="stats-grid">
				<view class="stat-item">
					<text class="stat-number">{{ totalCount }}</text>
					<text class="stat-label">总计</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ completedCount }}</text>
					<text class="stat-label">已完成</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ pendingCount }}</text>
					<text class="stat-label">待完成</text>
				</view>
			</view>
		</view>

		<!-- 功能菜单区域 -->
		<view class="menu-section">
			<view class="menu-item" @click="goToTest">
				<text class="menu-text">API连接测试</text>
				<text class="menu-arrow">></text>
			</view>
			<view class="menu-item" @click="clearAllData">
				<text class="menu-text">清空所有数据</text>
				<text class="menu-arrow">></text>
			</view>
			<view class="menu-item" @click="handleLogout">
				<text class="menu-text logout-text">退出登录</text>
				<text class="menu-arrow">></text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userInfo: {},
			todoList: []
		}
	},
	computed: {
		totalCount() {
			return this.todoList.length;
		},
		completedCount() {
			return this.todoList.filter(t => t.completed).length;
		},
		pendingCount() {
			return this.todoList.filter(t => !t.completed).length;
		}
	},
	onShow() {
		this.loadUserInfo();
		this.loadTodoList();
	},
	methods: {
		// 获取头像显示文字
		getAvatarText() {
			if (this.userInfo.nickname) {
				// 如果有昵称，显示昵称的最后一个字符
				return this.userInfo.nickname.slice(-1);
			} else if (this.userInfo.phone) {
				// 获取原始手机号用于头像显示
				let phone = this.userInfo.phone.toString();
				
				// 如果有原始手机号字段，优先使用
				if (this.userInfo.originalPhone) {
					phone = this.userInfo.originalPhone.toString();
				}
				
				// 移除非数字字符
				phone = phone.replace(/\D/g, '');
				
				// 如果手机号长度足够，显示后4位
				if (phone.length >= 4) {
					return phone.slice(-4);
				} else if (phone.length > 0) {
					return phone;
				} else {
					return 'U';
				}
			} else {
				// 都没有则显示默认字符
				return 'U';
			}
		},
		
		// 获取脱敏手机号
		getMaskedPhone() {
			if (!this.userInfo.phone) {
				return '';
			}
			
			let phone = this.userInfo.phone.toString();
			
			// 如果手机号看起来是加密的（包含特殊字符或长度异常），尝试使用原始手机号
			if (this.userInfo.originalPhone) {
				phone = this.userInfo.originalPhone.toString();
			}
			
			// 移除所有非数字字符
			phone = phone.replace(/\D/g, '');
			
			// 检查是否为有效的11位手机号
			if (phone.length === 11 && /^1[3-9]\d{9}$/.test(phone)) {
				// 格式：138****0000
				return phone.substring(0, 3) + '****' + phone.substring(7);
			} else if (phone.length >= 7) {
				// 如果不是标准11位但长度足够，显示前3位和后4位
				return phone.substring(0, 3) + '****' + phone.substring(phone.length - 4);
			} else if (phone.length >= 3) {
				// 号码较短，只显示前面部分
				return phone.substring(0, 3) + '****';
			} else {
				// 号码太短或无效，返回默认格式
				return '***';
			}
		},
		
		async loadUserInfo() {
			try {
				// 先从本地存储获取基本信息
				const localUserInfo = uni.getStorageSync('userInfo') || {};
				this.userInfo = localUserInfo;
				
				// 然后从API获取完整的用户信息（包含原始手机号）
				const { getUserInfo } = await import('../../api/user');
				const response = await getUserInfo();
				
				if (response && response.code === 200 && response.data) {
					// 更新用户信息，特别是原始手机号
					this.userInfo = {
						...this.userInfo,
						...response.data
					};
					
					// 同时更新本地存储（但保持手机号为原始格式用于脱敏显示）
					const updatedUserInfo = { ...response.data };
					uni.setStorageSync('userInfo', updatedUserInfo);
				}
			} catch (error) {
				console.error('获取用户信息失败:', error);
				// 如果API调用失败，继续使用本地存储的信息
				this.userInfo = uni.getStorageSync('userInfo') || {};
			}
		},
		
		loadTodoList() {
			this.todoList = uni.getStorageSync('todoList') || [];
		},
		
		goToTest() {
			uni.navigateTo({ url: '/pages/test/test' });
		},
		
		clearAllData() {
			uni.showModal({
				title: '确认清空',
				content: '您确定要清空所有待办事项吗？此操作不可恢复。',
				success: (res) => {
					if (res.confirm) {
						uni.setStorageSync('todoList', []);
						this.todoList = [];
						uni.showToast({
							title: '清空成功',
							icon: 'success'
						});
					}
				}
			});
		},
		
		handleLogout() {
			uni.showModal({
				title: '确认退出',
				content: '您确定要退出登录吗？',
				success: (res) => {
					if (res.confirm) {
						// 清除登录状态
						uni.removeStorageSync('isLoggedIn');
						uni.removeStorageSync('userInfo');
						
						uni.showToast({
							title: '已退出登录',
							icon: 'success'
						});
						
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}, 800);
					}
				}
			});
		}
	}
}
</script>

<style>
.profile-container {
	background-color: #f7f8fa;
	min-height: 100vh;
}

.user-info-section {
	display: flex;
	align-items: center;
	padding: 60rpx 30rpx 40rpx;
	background-color: #fff;
	margin-bottom: 20rpx;
}

.avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	margin-right: 30rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.avatar-text {
	color: white;
	font-size: 48rpx;
	font-weight: 600;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.user-details {
	display: flex;
	flex-direction: column;
}

.nickname {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
}

.phone {
	font-size: 28rpx;
	color: #999;
}

.stats-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.stats-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 30rpx;
}

.stats-grid {
	display: flex;
	justify-content: space-around;
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.stat-number {
	font-size: 48rpx;
	font-weight: bold;
	color: #007AFF;
	margin-bottom: 10rpx;
}

.stat-label {
	font-size: 24rpx;
	color: #999;
}

.menu-section {
	background-color: #fff;
}

.menu-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
	border-bottom: none;
}

.menu-text {
	font-size: 30rpx;
	color: #333;
}

.logout-text {
	color: #fa3534;
}

.menu-arrow {
	font-size: 28rpx;
	color: #ccc;
}
</style> 